<script setup>
import {ElMessage, ElMessageBox} from "element-plus";
import {sendWsRequest} from "@/api/toMusicInfo.js";
import {computed, nextTick, onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {loadSessionList, openSession, removeSession} from "@/api/privateMessage/session.js";
import {loadRecord} from "@/api/privateMessage/message.js";

const timeout = 180000; // 3分钟超时时间
var messageSocket;
var sessionSocket;
const router = useRouter()
const chatContainer = ref()
const ACCOUNT = localStorage.getItem('account')
const AVATAR = localStorage.getItem('avatar')
const showScrollButton = ref(false);  // 控制按钮显示的标志

const handleScroll = () => {
  const container = chatContainer.value.wrapRef;
  const distanceToBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
  showScrollButton.value = distanceToBottom > container.clientHeight;  // 如果距离大于一个容器高度，显示按钮
}

function scrollBottom() {
  if (chatContainer.value) {
    const scrollHeight = chatContainer.value.wrapRef.scrollHeight
    chatContainer.value.setScrollTop(scrollHeight);
  }
}
function onMessageScrollBottom() {
  if (chatContainer.value) {
    const scrollHeight = chatContainer.value.wrapRef.scrollHeight
    const clientHeight = chatContainer.value.wrapRef.clientHeight // 可视区域高度
    const scrollTop = chatContainer.value.wrapRef.scrollTop

    // 计算当前位置距离底部的距离
    const distanceToBottom = scrollHeight - scrollTop - clientHeight

    // 如果距离小于一个容器高度，才滚动到底部
    if (distanceToBottom <= clientHeight) {
      chatContainer.value.setScrollTop(scrollHeight);
    }

  }
}
onMounted(async () => {

  const data = {
    myAccount: localStorage.getItem('account'),
    otherAccount: route.query.toAccount
  }
  await openSession(data)
  // 然后加载会话列表
  await loadSessionList(localStorage.getItem('account')).then((res) => {
    messageRecords.value = res.data


    const find = messageRecords.value.find(record => record.toAccount === route.query.toAccount)




    // 看找没找到
    if (find != null) {
      activeAccount.value = route.query.toAccount
      activeSession.value = find.id
      activeName.value = find.toName
      activeAvatar.value = find.toAvatar
    } else {
      activeAccount.value = null
      activeSession.value = null
      activeName.value = null
      activeAvatar.value = null
      // todo 然后显示空信息即可

    }


  })

  messageSocket = new WebSocket('ws://localhost:20000/user/ws/message/' + localStorage.getItem('account'))

  messageSocket.onopen = (event) => {
    // console.log('messageSocket连接已建立')
    resetTimer()
  }

  messageSocket.onmessage = (event) => {
    resetTimer()

    const jsonData = JSON.parse(event.data)
    // 进行push数据
    console.log(jsonData)

    let targetRecords;

    if (ACCOUNT == jsonData.account) {
      console.log('true')
      // 我是发消息的人
      targetRecords = messageRecords.value.find(record => record.toAccount == jsonData.toAccount).records
    } else {
      console.log('false')
      targetRecords = messageRecords.value.find(record => record.toAccount == jsonData.account).records



    }
    console.log(targetRecords)

    if (targetRecords != undefined) {
      // 只有在发送方可以找到被发送方的会话账号

      targetRecords.push(jsonData)
    }

    // 确保 DOM 更新完成后，将容器滚动到底部
    nextTick(() => {
      onMessageScrollBottom()
    })
  }

  messageSocket.onclose = (event) => {

    // reload()
  }
  messageSocket.onerror = (event) => {
    console.log('连接出错:', event);
  }

  sessionSocket = new WebSocket('ws://localhost:20000/user/ws/session/' + localStorage.getItem('account'))

  sessionSocket.onopen = (event) => {
    resetTimer()
    console.log('sessionSocket连接已建立');
  }

  sessionSocket.onmessage = (event) => {
    resetTimer()

    const jsonData = JSON.parse(event.data)
    console.log(jsonData)

    if (jsonData.type == 0) {
      let tempRecord = messageRecords.value.find(record => record.toAccount == jsonData.toAccount)
      tempRecord.noticeNum = 0
      return
    }

    if (ACCOUNT == jsonData.account) {

      // 我是发消息的人，需要把消息数字清零，但是其实是第二层保障而已，因为在点击到这个会话的时候就已经清零了
      // 还有simpleMessage和recentTime
      const tempRecord = messageRecords.value.find(record => record.toAccount == jsonData.toAccount)

      const tempRecordIndex = messageRecords.value.findIndex(record => record.toAccount == jsonData.toAccount)
      if (tempRecordIndex !== -1) {
        // 将找到的元素移到数组开头
        const [tempRecord] = messageRecords.value.splice(tempRecordIndex, 1) // 从数组中移除该元素
        messageRecords.value.unshift(tempRecord) // 将该元素添加到数组的第一位
      }

      // if (tempRecord) {
      //   // 从数组中移除找到的记录
      //   messageRecords.value = messageRecords.value.filter(record => record.toAccount != jsonData.toAccount)
      //   // 将记录插入到数组的第一位
      //   messageRecords.value.unshift(tempRecord);
      // }
      tempRecord.recentTime = jsonData.recentTime
      tempRecord.simpleMessage = jsonData.simpleMessage
      tempRecord.noticeNum = 0

      console.log(tempRecord)
    } else {

      // let tempRecord = messageRecords.value.find(record => record.toAccount == jsonData.account)
      let tempRecord = {
        id: jsonData.id,
        toAccount: jsonData.account,
        toName: jsonData.toName,
        toAvatar: jsonData.toAvatar,
        simpleMessage: jsonData.simpleMessage,
        recentTime: jsonData.recentTime,
        noticeNum: jsonData.noticeNum,
        records: [
          {
            // type: 0,
            // data: ''
          }
        ]
      }


      const tempRecordIndex = messageRecords.value.findIndex(record => record.id == jsonData.id)
      console.log(tempRecordIndex)
      if (tempRecordIndex !== -1) {
        // 找到的话就删除，然后移动到首部
        // 将找到的元素移到数组开头
        const [tempRecord1] = messageRecords.value.splice(tempRecordIndex, 1) // 从数组中移除该元素
        messageRecords.value.unshift(tempRecord)
      } else {
        messageRecords.value.unshift(tempRecord)
      }




    }


    console.log(event.data);
  }
  sessionSocket.onclose = (event) => {

    // reload()
  }
  sessionSocket.onerror = (event) => {
    console.log('连接出错:', event);
  }

  // 加载消息记录
  await loadRecord(activeSession.value).then((res) => {
    // 在前端去找对应的
    // console.log(messageRecords.value.find(record => record.id == activeSession.value))
    messageRecords.value.find(record => record.id == activeSession.value).records = res.data

  })

  await nextTick(() => {
    scrollBottom()
  })

})


let timer
const route = useRoute()



const sendMessage = async (type) => {

  if (activeAccount.value == null) {
    // 请你指定联系人
    ElMessage.error('请你指定联系人')
    return
  }


  resetTimer()
  const now = Date.now()
  const messageData = {
    type: type,
    account: localStorage.getItem('account'),
    toAccount: activeAccount.value,
    sessionId: activeSession.value,
    sendTime: now,
    data: {
      message: message.value,
    }
  }

  let simpleMessage
  if (type === 0) simpleMessage = message.value
  else if (type === 1) simpleMessage = "图片消息"
  else if (type === 2) simpleMessage = "卡片消息"

  const sessionData = {
    simpleMessage: simpleMessage,
    account: localStorage.getItem('account'),
    toAccount: activeAccount.value,
    sessionId: activeSession.value,
    recentTime: now
  }




  sendWsRequest(messageSocket, messageData)

  sendWsRequest(sessionSocket, sessionData)

  message.value = ''
}


function resetTimer() {
  if (timer != null) clearTimeout(timer)
  // 连接超时处理
  timer = setTimeout(() => {
    messageSocket.close()
    sessionSocket.close()
    console.log('连接超时，已关闭')
    reload()
  }, timeout)
}

function reload() {
  ElMessageBox.confirm(
      '连接中断，请刷新重试',
      '连接断开',
      {
        confirmButtonText: '刷新',
        type: 'warning',
        showCancelButton: false,
        showClose: false,
        autofocus: true
      }
  )
      .then(() => {
        window.location.reload();
      })
}
const message = ref("")

const cssStyle = {
  background: 'inherit!important',
  outline: 'none!important',
  border: 'none',
  height: '100%',
  minWidth: '100%',
  boxShadow: 'none',
  fontSize: '14px',
  padding: '0'
}


// 总聊天记录
const messageRecords = ref([
  {
    id: '',
    toAccount: '',
    toName: '',
    toAvatar: '',
    simpleMessage: '默认消息',
    recentTime: '',
    noticeNum: 0,
    records: [
      {
          type: 0,
          data: ''
      }
    ]
  }
])

const messageRecord = computed(() => {
  const foundRecord = messageRecords.value.find(record => record.id == activeSession.value)
  if (foundRecord) {
    return foundRecord.records
  } else {
    return [] // 返回一个空数组作为安全值
  }
})

const activeAccount = ref()
const activeSession = ref()
const activeName = ref()
const activeAvatar = ref()

const closeSession = (id, toAccount) => {
  const data = {
    account: localStorage.getItem('account'),
    toAccount: toAccount
  }
  removeSession(data).then((res) => {
    // 删除成功后的操作，把记录删除掉
    messageRecords.value = messageRecords.value.filter(record => record.id!== id);
    ElMessage.success('删除成功')
  })

}

const viewStyle = {
  padding: '10px 21px',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'flex-start',
  gap: '10px',

}
const badgeStyle = {
  fontSize: '10px',
  height: '14px',
  lineHeight: '14px',
  backgroundImage: 'linear-gradient(121deg, #ff602d, #ff4000 93%)',
  padding: '0 4px',
  border: 'none'
}

const switchUser = async (item) => {
  activeAccount.value = item.toAccount
  activeSession.value = item.id
  activeName.value = item.toName
  activeAvatar.value = item.toAvatar

  await loadRecord(activeSession.value).then((res) => {
    // 在前端去找对应的
    // console.log(messageRecords.value.find(record => record.id == activeSession.value))
    messageRecords.value.find(record => record.id == activeSession.value).records = res.data

  })
  const data = {
    type: 0,
    id: activeSession.value,
    account: ACCOUNT,
    toAccount: activeAccount.value
  }
  sendWsRequest(sessionSocket, data)

  await nextTick(() => {
    scrollBottom()
  })

}
const formatSmartDate = (date) => {
  if (!date) return "";

  const now = new Date();
  const inputDate = new Date(date);

  const isSameDay = inputDate.toDateString() === now.toDateString();
  const isYesterday = new Date(now.setDate(now.getDate() - 1)).toDateString() === inputDate.toDateString();
  now.setDate(now.getDate() + 1); // 恢复当前时间

  const isSameYear = inputDate.getFullYear() === now.getFullYear();

  if (isSameDay) {
    return `${inputDate.getHours().toString().padStart(2, '0')}:${inputDate.getMinutes().toString().padStart(2, '0')}`;
  }
  else if (isYesterday) {
    return "昨天";
  }
  else if (isSameYear) {
    return `${(inputDate.getMonth() + 1).toString().padStart(2, '0')}/${inputDate.getDate().toString().padStart(2, '0')}`;
  }
  else {
    return `${inputDate.getFullYear()}/${(inputDate.getMonth() + 1).toString().padStart(2, '0')}/${inputDate.getDate().toString().padStart(2, '0')}`;
  }
}

function gotoHomePage(account) {
  if (account != null) {
    router.push('//mine/like?account=' + account)
  }

}
</script>

<template>

  <div class="bg">
    <el-container class="container">
      <el-aside class="left" width="200px">
        <p style="text-align: left;font-size: 12px;padding: 18px">
          <i class="fa-regular fa-comments fa-shake"></i>
          <span style="margin-left: 5px">私信列表</span>
        </p>
        <el-scrollbar style="cursor:pointer;display: flex;flex-direction: column;">
          <div @click="switchUser(item)" :class="{ active: activeAccount === item.toAccount}" v-for="(item, index) in messageRecords" class="session">
            <el-icon @click.stop="closeSession(item.id, item.toAccount)" size="9px" style="margin: 1px"><Close /></el-icon>

            <img width="36" style="border-radius: 50%" :src="item.toAvatar">
            <div style="width: 100%;margin-left: 10px;display: flex;flex-direction: column;gap: 5px;align-items: flex-start">
              <div style="height: 14px;line-height: 14px;align-items: center;width: 100%;display: flex;justify-content: space-between">
                <div style="font-size: 14px">{{ item.toName }}</div>
                <div style="text-align: right;color: #8a8a8a;font-size: 10px;margin-right: 10px">{{ formatSmartDate(item.recentTime) }}</div>
              </div>
              <div style="display: flex;justify-content: space-between;width: 100%;line-height: 14px;height: 14px">
                <div style="font-size: 11px;color: #797979">{{ item.simpleMessage }}</div>
                <el-badge style="margin-right: 10px" :badge-style="badgeStyle" :show-zero=false :max="99" :value=item.noticeNum />
              </div>

            </div>
          </div>
        </el-scrollbar>

      </el-aside>
      <el-container class="right">
          <el-header style="color: #333;
    font-family: PingFangSC-Medium;
    font-size: 16px;
    height: 29px;
    line-height: 29px;padding-left: 0;
    letter-spacing: 0;
    margin-bottom: 5px;
    width: 100%;">{{ activeName }}</el-header>

          <div style="display: flex;height: calc(100% - 29px);overflow: hidden">

            <div style="flex: 3;display: flex;flex-direction: column">


                <!-- 这里加载获取会话的消息 -->
              <el-scrollbar @scroll="handleScroll" ref="chatContainer" :view-style="viewStyle"
                            style="position: relative;flex: 2;border-bottom: 1px solid #d5dae0;border-top: 1px solid #d5dae0;">

                <div v-for="(item, index) in messageRecord" style="gap: 10px;align-items: flex-start;max-width: 60%;"
                     :class="{ own : item.account == ACCOUNT, other : item.account != ACCOUNT}"
                >
                  <img width="36" height="" style="display: inline-block;border-radius: 50%" :src="item.account == ACCOUNT ? AVATAR :activeAvatar">
                  <div class="message">
                    <div class="name">{{ item.account == ACCOUNT ? '我' : activeName}}</div>
                    <div :class="{'own-message': item.account == ACCOUNT, 'other-message' : item.account != ACCOUNT}">
                      <!-- todo 根据不同type进行不同操作 -->
                      <span>{{ item.data.message }}</span>

                    </div>
                  </div>

                </div>

                <button v-show="showScrollButton" @click="scrollBottom"
                         style="display: flex;align-items: center;gap: 3px;cursor:pointer;background-color: rgba(234,164,112,0.2);color: #e97561;border: none;outline: none;border-radius: 14px;padding: 3px 16px 4px 12px;font-size: 12px;
                         ;box-shadow: 0 0 5px 0 rgba(51,51,51,0.5);position: absolute;right: 10px;bottom: 10px" >
                  <el-icon><Bottom /></el-icon>返回底部
                </button>

              </el-scrollbar>

              <el-footer style="flex: 1; box-sizing: border-box;padding: 10px 10px 10px 0;display: flex;flex-direction: column; position: relative;">
                <div style="line-height: 20px;height: 20px;display: flex">
                  <span >工具栏</span>
                  <div class="word-limit">{{ message.length }} / 500</div>

                </div>
                <el-input
                    v-model="message"
                    maxlength="500"
                    style="flex: 1"
                    :input-style=cssStyle
                    placeholder="请输入消息，按Enter键 或 点击发送按钮发送"
                    type="textarea"
                    resize="none"
                />

                <button @click="sendMessage(0)" class="send-button">
                    发送
                </button>

              </el-footer>



            </div>

            <div style="flex: 1;border-bottom-right-radius: 12px;
    border-top-right-radius: 12px;padding: 20px;width: 100%;margin-left: 10px;background: white;">
<!--              <el-button @click="reload">click</el-button>-->
<!--              {{ messageRecord}}-->
              <div style="display: flex">
                <img width="60" height="60" style="border-radius: 5px;margin-right: 10px" :src="activeAvatar">
                <div style="display: flex;flex-direction: column;justify-content: space-between;align-items: flex-start">
                  <el-text style="align-self: flex-start;max-width: 80px;font-size: 15px;color: #333333" line-clamp="2">{{ activeName }}</el-text>
                  <el-button @click="gotoHomePage(activeAccount)" size="small" style="background-color: var(--el-button-hover-bg-color);border-color: var(--el-button-hover-border-color);color: var(--el-button-hover-text-color);outline: none;">进入主页</el-button>
                </div>
              </div>
<!--              <el-tag size="small" type="warning" round style="margin-left: 7px">音乐人</el-tag>-->

            </div>

          </div>


      </el-container>

    </el-container>

  </div>


</template>

<style scoped>
.bg {
  width: 100vw;
  height: 100vh;
  background: url("/src/assets/img/message/bg.png") no-repeat;
  background-size: cover;

}
.container {
  background-color: #faf9f9;
  position: absolute;
  top: 50%;
  left: 50%;
  box-sizing: border-box;
  min-height: 587px;
  height: 587px;
  max-height: 587px;
  transform: translate(-50%,-50%);
  box-shadow: #b4b4b4 0 0 10px 0;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
}
.send-button {
  background-color: #e7e7e8;
  color: #e96161;
  position: absolute;
  right: 8px;
  bottom: 5px;
  border: none;
  border-radius: 5px;
  padding: 7px 30px;
  font-size: 16px;
  cursor: pointer;
}
.word-limit {
  margin-left: auto;

  font-size: 12px;
  color: #999;
}
.left {
  width: 270px;
  background-color: #f5f6f9;
  text-align: center;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
  border-right: 1px solid #eee;
}
.left:hover {
  overflow: auto;
}
.right {
  display: flex;
  flex-direction: column;
  width: 845px;
  box-sizing: border-box;
  padding: 20px 20px 14px;
  background: #f0f2f5;
}

.session {
  background: white;
  display: flex;
  height: 54px;
  margin-left: 10px;
  align-items: center;
}
.session:hover {
  background-image: linear-gradient(98deg, #fff7ee 29%, #fbf3ea)!important;
  border-radius: 4px;
}
.session i {
  opacity: 0;
}
.session:hover i {
  opacity: 1;
}
.active {
  background: #e6e9ed;
}
.message {
  display: flex;
  flex-direction: column;
  gap: 5px;

  font-size: 14px;
}
.other {
  display: flex;
  align-self: flex-start;
}
.own{
  display: flex;
  flex-direction: row-reverse;
  align-self: flex-end;
  text-align: right;
}
.own .name {
  color: #999999;
  font-size: 12px;
}
.other .name {
  color: rgb(48, 63, 159);
  font-size: 12px;
}
.other-message {
  background-color: white;
  padding: 8px;
  border-radius: 5px;
  word-wrap: break-word;
  overflow-wrap: break-word;
}
.own-message {
  background-color: #ffe9e9;
  border-radius: 5px;
  padding: 8px;
  text-align: left;
  word-wrap: break-word;
  overflow-wrap: break-word;
}
</style>
